package com.erp.util;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;

import com.alibaba.appengine.api.fetchurl.FetchUrlService;
import com.alibaba.appengine.api.fetchurl.FetchUrlServiceFactory;
import com.erp.dto.IpLocation;

public class IpUtil {

	/**
	 * 通过ACE的API访问外网
	 */
	public static final int ACE = 0;
	/**
	 * HttpClient直接连接外网
	 */
	public static final int DIRECT = 1;
	/**
	 * 使用代理方式访问外网
	 */
	public static final int PROXY = 2;

	/**
	 * 根据IP查地理位置（淘宝API）
	 * 
	 * @param ip
	 *            IP地址
	 * @param type
	 *            访问方式（ACE的API，直接访问、通过代理）
	 * @return
	 */
	public static IpLocation getIpLocationByIp(String ip, int type) {

		String jsonStr = null;
		IpLocation ipLocation = null;

		switch (type) {
		case ACE:
			jsonStr = fetchUrlUseACE(ip);
			break;

		case DIRECT:
			jsonStr = fetchUrlUseHttpClient(ip);
			break;

		case PROXY:

			break;

		default:
			break;
		}
		if (jsonStr == null) {
			return null;
		}
		JSONObject jsonObj = JSONObject.fromObject(jsonStr);
		Integer code = (Integer) jsonObj.get("code");
		JSONObject dataObj = null;
		// code的值的含义为:0：成功，1：失败。
		// data的值的含义为:国家 、省（自治区或直辖市）、市（县）、运营商
		if (code.intValue() == 0) {
			dataObj = JSONObject.fromObject(jsonObj.get("data"));
			ipLocation = (IpLocation) JSONObject.toBean(dataObj,
					IpLocation.class);
		}
		return ipLocation;
	}

	/**
	 * 通过HttpClient访问外网（非代理）
	 * 
	 * @param ip
	 * @return
	 */
	public static String fetchUrlUseHttpClient(String ip) {
		HttpClient client = new HttpClient();
		String host = "ip.taobao.com";
		client.getHostConfiguration().setHost(host, 80, "http");
		HttpMethod method = new GetMethod("/service/getIpInfo.php?ip=" + ip);
		String response = null;
		try {
			client.executeMethod(method);
			// 打印服务器返回的状态
			// System.out.println(method.getStatusLine());
			response = new String(method.getResponseBodyAsString().getBytes(
					"utf-8"));
			method.releaseConnection();

		} catch (Exception e) {
			System.out.println("获取IP所在地失败！");
			e.printStackTrace();
		}
		return response;
	}

	/**
	 * ACE线上环境不能直接访问外网。 HTTP请求需要通过使用 网页代理
	 * 
	 * 或可通过ACE的api访问外网
	 * 
	 * @return
	 */
	public static String fetchUrlUseACE(String ip) {
		FetchUrlService fetchUrlService = FetchUrlServiceFactory
				.getFetchUrlService();
		final String url = "http://ip.taobao.com/service/getIpInfo.php?ip="
				+ ip;
		String response = fetchUrlService.get(url);
		return response;
	}
}
